package com.cookie.controller;

import com.alibaba.fastjson.JSON;
import com.cookie.common.utils.FileUploadUtils;
import com.cookie.common.utils.Result;
import com.cookie.common.validator.ValidatorUtils;
import com.cookie.entity.HistoryPaper;
import com.cookie.entity.Issues;
import com.cookie.entity.User;
import com.cookie.service.WxApiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @author : cookie ✌️
 * @date : 2018/11/3 9:42
 */
@RestController
@RequestMapping("wx/api/")
public class WxApiController {

    @Autowired
    private WxApiService wxApiService;

    /**
     * 根据分类查询试卷
     *
     * @param types 试卷类型
     * @return a string
     */
    @GetMapping("queryPapers")
    public String queryPapers(String types) {
        return wxApiService.queryPapers(types);
    }

    /**
     * 文件上传
     *
     * @param files 文件
     * @return a String
     */
    @PostMapping("uploadImage")
    public Result uploadImage(@RequestParam("files") MultipartFile files) {
        String issues = FileUploadUtils.writeUploadFile(files, "issues");
        return Result.ok(issues);
    }

    /**
     * 查询做题历史
     *
     * @param userId 用户id
     * @return a string
     */
    @GetMapping("hPapers")
    public String hPapers(String userId) {
        List<HistoryPaper> historyPapers = wxApiService.hPapers(userId);
        return JSON.toJSONString(historyPapers);
    }


    /**
     * 保存反馈记录
     *
     * @return Result
     */
    @PostMapping("issues")
    public Result saveIssues(@RequestBody Issues issues) {
        //表单校验
        ValidatorUtils.validateEntity(issues);
        return wxApiService.saveIssues(issues);
    }

    /**
     * 查询反馈条数
     *
     * @param userId 用户id
     * @return r
     */
    @PostMapping("issuesCount")
    public Result issuesCount(String userId) {
        return wxApiService.issuesCount(userId);
    }

    /**
     * 编辑用户信息保存
     *
     * @param user 用户信息
     * @return new Result()
     */
    @PostMapping("saveUserInfo")
    public Result editUserInfo(@RequestBody User user) {
        return wxApiService.editUserInfo(user);
    }

    /**
     * 根据试卷id查询对映试题
     *
     * @param paperId 试卷id
     * @return new Result()
     */
    @GetMapping("queryQuestions")
    public Result queryQuestions(Integer paperId, String category, @RequestParam(name = "page", defaultValue = "1") int page) {
        if (page > 75) {
            return Result.ok("已经到最后一页了");
        }
        return wxApiService.queryQuestions(paperId, category, page);
    }
}
